package com.tools.web;

import com.tools.common.object.Note;
import com.tools.web.filter.gateway.GetawayFilter;
import com.tools.web.interceptor.auth.AuthUser;
import com.tools.web.interceptor.auth.AuthenticationManager;
import javax.servlet.http.HttpServletRequest;

/**
 * 公用工具类。
 * 值得注意很多方法需要身份认证后才能获取到，否则会出现异常
 * */
@Note("公用工具类。值得注意很多方法需要身份认证后才能获取到，" +
        "否则会出现异常")
public class GlobalKit {


    @Note("获取当前请求的 IP 地址")
    public static String getClientIP(HttpServletRequest request) {
        return (String) request.getAttribute(WebKit.CLIENT_IP_NAME);
    }

    @Note("获取当前请求的 IP 地址")
    public static String getClientIP() {
        return getClientIP(WebKit.getHttpServletRequest());
    }

    @Note("获取自定义得到的客户端外网 IP （不是很准确）")
    public static String getPublicClientIP(HttpServletRequest request) {
        return (String) request.getAttribute(GetawayFilter.PUBLIC_NET_IP_NAME);
    }

    @Note("获取自定义得到的客户端外网 IP （不是很准确）")
    public static String getPublicClientIP() {
        return getPublicClientIP(WebKit.getHttpServletRequest());
    }

    @Note("获取当前用户封装的 AuthUser 对象")
    public static AuthUser getAuthUser(HttpServletRequest request) {
        return (AuthUser) request.getAttribute(AuthenticationManager.USER_DATA_NAME);
    }

    @Note("获取当前用户封装的 AuthUser 对象")
    public static AuthUser getAuthUser() {
        return getAuthUser(WebKit.getHttpServletRequest());
    }


    @Note("获取 int 类型当前用户的主键 ID")
    public static Integer getIntUserId(HttpServletRequest request) {
        return getAuthUser(request).getUserId(Integer.class);
    }

    @Note("获取 int 类型当前用户的主键 ID")
    public static Integer getIntUserId() {
        return getIntUserId(WebKit.getHttpServletRequest());
    }

    @Note("获取 long 类型当前用户的主键 ID")
    public static Long getLongUserId(HttpServletRequest request) {
        return getAuthUser(request).getUserId(Long.class);
    }

    @Note("获取 long 类型当前用户的主键 ID")
    public static Long getLongUserId() {
        return getLongUserId(WebKit.getHttpServletRequest());
    }

    @Note("获取 String 类型当前用户的主键 ID")
    public static String getStringUserId(HttpServletRequest request) {
        return getAuthUser(request).getUserId().toString();
    }

    @Note("获取 String 类型当前用户的主键 ID")
    public static String getStringUserId() {
        return getStringUserId(WebKit.getHttpServletRequest());
    }

    @Note("已经认证后，可以从请求对象中获取设备类型 ID")
    public static String getDeviceTypeId(HttpServletRequest request) {
        return getAuthUser(request).getDeviceTypeId();
    }

    @Note("已经认证后，可以从请求对象中获取用户类型")
    public static String getUserType(HttpServletRequest request) {
        return getAuthUser(request).getUserType();
    }
}
